//回款记录列表table
var $returnMoneyTableList = $('#returnMoneyTable');
// 产品列表table
var $productTable = $('#productList');
// 已删产品table
var $selectedTable = $('#selectedList');
//页面结尾按钮提交删除审核按钮
var $btnRightDel=$('#btnRightDel')
//回款修改记录
var $orderCollection=$('#orderCollection');
// 产品删除记录北京财税研究院
var $productDelRecord=$('#productDelRecord')
//部分回款字段
var partialPayment = {};

var partialPaymentBtn;

//错误修改
var $errorCorrectionTable = $('#errorCorrectionTable');

$(function () {
    /*if(($('#orderFinish').val() == 2 || $('#orderFinish').val() == 4) && $('#deptId').val() == '3'){
        $('#payBackBtn').hide()
        $('#dismissBtn').show()
    }else{
        $('#payBackBtn').show()
        $('#dismissBtn').hide()
    }*/
    if($('#orderFinish').val() == 1){
        $('#payBackBtn').show()
    }else{
        $('#payBackBtn').hide()
    }
    if($('#orderFinish').val() == 2||$('#orderFinish').val() == 4){
        $('#dismissBtn').show()
    }else{
        $('#dismissBtn').hide()
    }
    //初始化控件
    dateModule();


    //getCustomerSelect();

    // loadAllCompanyList("paymentUnit");

    //loadAllCompanyList("filialeId");

    loadCompanyList();

    getReturnMoneyList();

    productList();
    productCollection();
    //productDeletion();

    //判斷是否需要展示訂單完成標識
    orderIsFinish();

    $("#shiftInfoDiv").hide();
    //初始化已删除列表
    $selectedTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //search: true,
        //visibleSearch: true,
        pagination: true,
        pageSize: 5,
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        columns: [
            {field: 'customerProductId', title: 'id', visible: false},
            {field: 'productName', title: '产品名称'},
            {field: 'money', title: '价格'},
            {field: 'operate', title: '操作', width: '80', align: 'center'},
        ],
        formatNoMatches:function(){
            return "暂无产品";
        },
    });

    $('.modal').on('show.bs.modal', function () {
        $(this).find('.modal-dialog').draggable();
    });

    cooperateTable();
    cooperateTable1();
    $('#cooperateModal').on('show.bs.modal', function () {
        $('#cooperateTable').bootstrapTable('showLoading');
        viewCooperate(1);
    });
    $('#cooperateModal2').on('show.bs.modal', function () {
        $('#cooperateTable').bootstrapTable('showLoading');
        viewCooperate2(2);
    });
    productDeletion();
    orderInfoList();//购买产品列表
    errorCorrectionTableInit();



});


//订单状态
function orderIsFinish() {
    var orderFinish = $("#orderFinish").val();
    if ("2" == orderFinish){
        $('.orderVoid2').show();
    }
    if ("1" == orderFinish){
        $('.orderVoid').show();
    }
    if ("3" == orderFinish){
        $('.orderVoid3').show();
    }
    if ("4" == orderFinish){
        $('.orderVoid4').show();
    }
    if ("5" == orderFinish){
        $('.orderVoid5').show();
    }
}

//查询订单回款记录
function getReturnMoneyList() {
    //先销毁表格
    $returnMoneyTableList.bootstrapTable('destroy');
    $returnMoneyTableList.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/returnMoney/selectReturnMoneyList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "asc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'returnMoneyId',
        idField: 'returnMoneyId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'returnMoneyId',visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '产品名称', field: 'productName', align: 'left', valign: 'middle'},
            {title: '流水号', field: 'serial', align: 'left', valign: 'middle'},
            {title: '产品号', field: 'finishOrderProductNum', align: 'left', valign: 'middle'},
            {title: '回款编号', field: 'arriveNum', align: 'left', valign: 'middle'},
            {title: '付款账号', field: 'paymentAccount', align: 'left', valign: 'middle'},
            {title: '付款单位', field: 'paymentUnitName', align: 'left', valign: 'middle'},
            {title: '到款时间',field: 'arriveTime', align: 'left', valign: 'middle'},
            {title: '到款金额',field: 'arriveMoney',align: 'left', valign: 'middle'},
            {title: '到款单位名称', field: 'arriveUnitName',align: 'left', valign: 'middle'},
            {title: '回款状态', field: 'returnStatus',align: 'left',valign: 'middle',
                formatter: function (value) {
                    let html = '';
                    if (value == 0) {
                        html += '预回款';
                    }else if (value == 1){
                        html += '正常';
                    }
                    return html;
                }
            },
            {title: '录入人', field: 'createByName',  align: 'left',valign: 'middle'},
            {title: '创建时间', field: 'createTm',  align: 'left',valign: 'middle'},
            // {title: '操作', field: 'operationThing',  align: 'right',valign: 'middle',formatter: enterPayMent},

        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            $('#customerProductTableList').css({
                minWidth: $('#customerProductTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });

}


function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.orderCode = $("#orderCode").val();
    return params;
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

//获取表格，新增表格名称：回款修改记录
function productCollection() {
    $orderCollection.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/returnMoneyLog/getReturnMoneyLogList',//请求地址
        method: 'get',
        // contentType: "application/x-www-form-urlencoded",//请求内容类型
        // dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "asc",//排序方式
        // sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'returnMoneyLogId',//设置每行唯一标识符
        idField: 'returnMoneyLogId',//指定主键列
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        queryParams: queryParams2,//查询参数
        columns:[
            {field: 'returnMoneyLogId', title: 'id', visible: false},
            {title: '回款编号', field: 'arriveNum', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operatorType',align: 'left', valign: 'middle', formatter: updateReturnMoneyType},
            {title: '修改前信息', field: 'formerData',align: 'left', valign: 'middle'},
            {title: '修改后信息', field: 'newData',align: 'left', valign: 'middle'},
            {title: '修改人', field: 'createPeopleName', align: 'left', valign: 'middle'},
            {title: '修改时间',field: 'createTm', sortable: true,align: 'left', valign: 'middle'}
        ],
        formatNoMatches:function () {
            return '暂无数据'
        },
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
    })
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    //搜索条件
    params.orderId = $("#orderCode").val();
    return params;
}

function updateReturnMoneyType(value, row, index) {
    var html = "";
    if (value ==1 ){
        html = "修改";
    }
    if (value ==2 ){
        html = "删除";
    }
    if (value ==3 ){
        html = "退款";
    }
    if (value ==4 ){
        html = "关联";
    }
    return html;
}

//回款错误关联
function shiftOrderReturnMoney() {
    $.alert({
        title: '提示',
        content: "确定要进行错误关联吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        url:'/returnMoney/shiftOrderReturnMoney',
                        type: 'POST',
                        dataType: "json",
                        data: {
                            orderId:$("#shiftReturnMoneyIdHide").val(),
                            shiftOrderNumber:$("#shiftOrderNumber").text()
                        },
                        success: (function (data) {
                            if(data.code == '000000'){
                                $.alert({
                                    title: '提示',
                                    content: '操作成功！',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                window.location.reload();
                                            }
                                        }
                                    }
                                });
                            }else {
                                $.alert(data.message);
                            }
                        }),
                        error: (function (res) {

                        })
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}

//取消重置
function hideInput() {
    // window.location.reload();
    $('#returnMoneyIdHide').val('') //回款id
    $('#arriveTime').val('') //到款时间
    $('#arriveMoney').val('') //到款金额
    $('#arriveMethod').val('').selectpicker('refresh'); //到款方式
    $('#arriveAccountType').val('').selectpicker('refresh'); //到款账号类型
    $('#remark').val('') //备注
    $('#paymentAccount').val('') //付款账号
    $('#paymentUnit').val('') //付款单位
    // $returnMoneyTableList.bootstrapTable('refresh');
}

/**
 * 加载回款公司信息
 */
function loadCompanyList() {
    var companyOptionHtml = '';
    var trueCompanyName = $("#companyNameId").val();
    if (trueCompanyName && trueCompanyName != "北京财税研究院" && trueCompanyName !="大成方略网络科技有限公司" && trueCompanyName !="北京大成方略财务顾问有限公司"
        && trueCompanyName != "北京大成方略纳税人俱乐部有限公司" && trueCompanyName !="大成方略纳税人俱乐部股份有限公司"){
        companyOptionHtml += '<option value="0">' + trueCompanyName + '</option>';
    }
    companyOptionHtml += '<option value="1">北京财税研究院</option>';
    companyOptionHtml += '<option value="2">大成方略网络科技有限公司</option>';
    companyOptionHtml += '<option value="3">北京大成方略财务顾问有限公司</option>';
    companyOptionHtml += '<option value="4">北京大成方略纳税人俱乐部有限公司</option>';
    companyOptionHtml += '<option value="5">大成方略纳税人俱乐部股份有限公司</option>';
    $('#arriveAccountType').html("");
    $('#arriveAccountType').append(companyOptionHtml);
    $('#arriveAccountType').selectpicker('refresh');
}

var pageIndex = 1;
function loadMore(){
    pageIndex++
    orderInfoList()
}

function orderInfoList(){
    $.ajax({
        url: '/finishOrderProduct/selectOrderFinishProduct',
        type: 'POST',
        dataType: "json",
        data: {
            pageIndex: pageIndex,
            pageSize:5,
            orderId:$('#orderCode').val()
        },
        success: (function (data) {
            if (data.code == "000000") {
                if(data.totalRecords > pageIndex*5){
                    $('.loadMoreLine').css('display','block')
                }else{
                    $('.loadMoreLine').css('display','none')
                }
                var html = '';
                $.each(data.data,function(index,item){
                    html =`<div class="buyProductList" style="margin-top: 10px">
                               <div class="buyProduct clearfix">
                                   <div class="buyProductName pull-left">
                                       <div class=${item.productCategories == 0?'noMember':'productType'}></div>
                                       <div class="productNum">产品编号：${item.finishOrderProductNum}</div>
                                   </div>
                                   <div class="buyProductDetails pull-right">
                                       <div class="productName" style="height: 50%">
                                           <div class="img pull-left" >
                                               <img src="/images/finance/orderInfo/icon2.png" alt="" class="pull-left" style="display: block">
                                               <div class="product_name pull-left" style="margin-left: 15px">
                                                   <p class="product_key">产品名称</p>
                                                   <p class="product_value">${item.productName}</p>
                                               </div>
                                           </div>
<!--                                           <div class="operateButton pull-right">-->
<!--                                               <button class="btn btn-primary ${item.residueMoney == 0?'isHide':'isShow' }" type="button" data-toggle="modal"  data-target="#addInputMoney" aria-expanded="false"  onclick="payBack('2','${item.productId}','${item.productCode}','${item.productName }','${item.productCategories}','${item.finishOrderProductNum}','${item.orderDetailType}','${item.finishOrderProductId}','${item.residueMoney}')" >产品回款</button>-->
                                              <!-- <button class="btn btn-default"  type="button" data-toggle="modal" data-target="#errorCorrectionModal" aria-expanded="false"  style="margin-left: 10px">错误修改</button>-->
<!--                                           </div>-->
                                       </div>
                                       <div class="productDetails pull-left" style="width: 100%">
                                           <div class="productDetailsItem  pull-left">
                                               <div class="img pull-left" style="margin-top: 10px">
                                                   <img src="/images/finance/orderInfo/icon3.png" alt="">
                                               </div>
                                               <div class="productDetailsList clearfix"  style="border-right: 1px solid #CCD2DB">
                                                   <div class="pull-left" style="width: calc(100% - 50px)">
                                                       <div class="productDetailsTitle">产品成交价</div>
                                                       <div class="productDetailsNum">${item.productFinalPrice}</div>
                                                   </div>
                                               </div>
                                           </div>
                                           <div class="productDetailsItem pull-left">
                                               <div class="img pull-left" style="margin-top: 10px">
                                                   <img src="/images/finance/orderInfo/icon4.png" alt="">
                                               </div>
                                               <div class="productDetailsList clearfix"  style="border-right: 1px solid #CCD2DB">
                                                   <div class="pull-left" style="width: calc(100% - 50px)">
                                                       <div class="productDetailsTitle">当前回款</div>
                                                       <div class="productDetailsNum">${item.paidMoney}</div>
                                                   </div>
                                               </div>
                                           </div>
                                           <div class="productDetailsItem  pull-left" >
                                               <div class="img pull-left" style="margin-top: 10px">
                                                   <img src="/images/finance/orderInfo/icon5.png" alt="">
                                               </div>
                                               <div class="productDetailsList clearfix">
                                                   <div class="pull-left" style="width: calc(100% - 50px)">
                                                       <div class="productDetailsTitle">当前尾款</div>
                                                       <div class="productDetailsNum">${item.residueMoney}</div>
                                                   </div>
                                               </div>
                                           </div>
                                       </div>
                
                                   </div>
                               </div>
                           </div>`
                    $('#buyProductList').append(html)
                })


            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}


function payBack(type,id,productNumber,productName,productCategories,finishOrderProductNum,orderDetailType,finishOrderProductId,residueMoney){
    $('#returnMoneyIdHide').val('') //回款id
    $('#arriveTime').val('') //到款时间
    $('#arriveMoney').val('') //到款金额
    $('#arriveAccountType').val('').selectpicker('refresh'); //到款账号类型
    $('#remark').val('') //备注
    $('#paymentUnit').val($('#customerName').val());
    $('#paymentAccount').val($('#paymentAccountVal').val())
    $('#arriveMethod').val('').selectpicker('refresh');
    $('#addInputMoney').modal('hide');
    if(type == 1){
        partialPaymentBtn = 0;
        $('#arriveMoney').val($('#balancePayment').html()).prop('disabled', true).css('font-weight', 'bold');
        $('#modalTitle').html('全部回款');
    } else {
        partialPaymentBtn = 1;
        $('#arriveMoney').prop('disabled', false).css('font-weight', 'normal');
        $('#modalTitle').html('产品回款');
    }
    partialPayment.productId = id;
    partialPayment.productNumber = productNumber;
    partialPayment.productName = productName;
    partialPayment.productCategories = productCategories;
    partialPayment.finishOrderProductNum = finishOrderProductNum;
    partialPayment.orderDetailType = orderDetailType;
    partialPayment.finishOrderProductId = finishOrderProductId;
    partialPayment.residueMoney = residueMoney;
}

function inputMoney(element) {
    var returnMoneyId = $.trim($('#returnMoneyIdHide').val());//回款id
    var arriveTime = $.trim($('#arriveTime').val());//回款日期
    var arriveMoney = $.trim($('#arriveMoney').val());//到款金额
    var arriveUnitName = $("#arriveAccountType").find("option:selected").text();//到款单位
    var paymentUnit = $.trim($('#paymentUnit').val());//付款单位
    var paymentAccount = $.trim($('#paymentAccount').val());//付款账号
    var arriveMethod = $.trim($('#arriveMethod').val());//到款方式
    var serial = $.trim($('#serial').val());//流水号
    var paymentBank = $.trim($('#paymentBank').val());//付款银行
    var arriveAccountType = $.trim($('#arriveAccountType').val());//到款账号类型
    var remark = $.trim($('#remark').val());//备注
    var orderId = $.trim($('#orderCode').val());//所属订单

    // if (accSubtr($("#residueMoneyAmountspan").text(),arriveMoney) != 0){
    //     promptInfo("根据公司规定，必须全额回款!");
    //     return;
    // }
    if (!arriveTime) {
        promptInfo("回款日期不能为空!");
        return;
    }
    if (!serial) {
        promptInfo("流水号不能为空!");
        return;
    }
    if ( 0.01 > arriveMoney){
        if (0.00 != $("#orderActualTotalAmount").text() && 0 != $("#orderActualTotalAmount").text()){
            promptInfo("到款金额不能为0!");
            return;
        }
    }
    if (!arriveMoney){
        promptInfo("到款金额不能为空!");
        return;
    }
    if (!paymentUnit) {
        promptInfo("付款单位不能为空!");
        return;
    }
    if (!arriveMethod) {
        promptInfo("到款方式不能为空!");
        return;
    }
    /*if (arriveMethod == 0) {
        if (!paymentBank){
            promptInfo("付款银行不能为空!");
            return;
        }
        if (!serial){
            promptInfo("流水号不能为空!");
            return;
        }
        if (!paymentAccount) {
            promptInfo("付款账号不能为空!");
            return;
        }
    }*/
    if (!arriveAccountType) {
        promptInfo("到款账号类型不能为空!");
        return;
    }
    if(partialPaymentBtn == 0){
        if(Number($('#arriveMoney').val()) > Number($('#residueMoneyAmountspan').val())){
            promptInfo("到款金额不能大于尾款!");
            return;
        }
    }

    if(partialPaymentBtn == 1){
        if(Number($('#arriveMoney').val()) > Number(partialPayment.residueMoney)){
            promptInfo("到款金额不能大于尾款!");
            return;
        }
    }

    $(element).prop('disabled', true);

    if(returnMoneyId == null || returnMoneyId == ""){
        var jsonData;
        if(partialPaymentBtn == 0){
            //新增回款
            jsonData = {
                "arriveType": 0,
                "arriveTime": arriveTime,
                "arriveMoney": arriveMoney,
                "arriveUnitName": arriveUnitName,
                "paymentUnit": paymentUnit,
                "paymentAccount": paymentAccount,
                "arriveMethod": arriveMethod,
                "arriveAccountType": arriveAccountType,
                "remark": remark,
                "serial": serial,
                "paymentBank": paymentBank,
                "orderId": orderId
            }
        }else{
            jsonData = {
                "arriveType": 1,
                "arriveTime": arriveTime,
                "arriveMoney": arriveMoney,
                "arriveUnitName": arriveUnitName,
                "paymentUnit": paymentUnit,
                "paymentAccount": paymentAccount,
                "arriveMethod": arriveMethod,
                "arriveAccountType": arriveAccountType,
                "remark": remark,
                "serial": serial,
                "paymentBank": paymentBank,
                "orderId": orderId,
                "productId":partialPayment.productId,
                "productNumber":partialPayment.productNumber,
                "productName":partialPayment.productName,
                "productCategories":partialPayment.productCategories,
                "finishOrderProductNum":partialPayment.finishOrderProductNum,
                "orderDetailType":partialPayment.orderDetailType,
                "finishOrderProductId":partialPayment.finishOrderProductId,
            }
        }
        $.ajax({
            url: '/returnMoney/addReturnMoneyJoinFlow',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if(data.code == '000000'){
                    $.alert({
                        title: '提示',
                        content: '保存成功！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    //页面跳转赋值
                                    // var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                    // var navTab = parent.$multitabs._getNavTab($thisTabs);
                                    window.location.reload();
                                    /*closeTab(navTab);
                                    openTab("回款记录","/front/receiptManager/userReceiptRecord");*/
                                    //delStorageAndRemove(navTab);
                                }
                            }
                        }
                    });
                }else {
                    $.alert(data.message);
                    $(element).prop('disabled', false);
                }
            }),
            error: (function (res) {
                $.alert("保存失败");
                $(element).prop('disabled', false);
            })
        })
    }else {
        //修改回款
        var jsonData = {
            "returnMoneyId":returnMoneyId,
            "arriveTime":arriveTime,
            "arriveMoney":arriveMoney,
            "arriveUnitName":arriveUnitName,
            "paymentUnit":paymentUnit,
            "paymentAccount":paymentAccount,
            "arriveMethod":arriveMethod,
            "arriveAccountType":arriveAccountType,
            "remark":remark,
            "serial":serial,
            "paymentBank":paymentBank,
            "orderId":orderId
        }

        $.ajax({
            url: '/returnMoney/updateReturnMoney',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if(data.code == '000000'){
                    $.alert({
                        title: '提示',
                        content: '保存成功！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    //页面跳转赋值
                                    // var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                    // var navTab = parent.$multitabs._getNavTab($thisTabs);
                                    window.location.reload();
                                    /*closeTab(navTab);
                                    openTab("回款记录","/front/receiptManager/userReceiptRecord");*/
                                    //delStorageAndRemove(navTab);
                                }
                            }
                        }
                    });
                }else {
                    $.alert(data.message);
                    $(element).prop('disabled', false);
                }
            }),
            error: (function (res) {
                $.alert("保存失败");
                $(element).prop('disabled', false);
            })
        })
    }


}

// 错误修改
function errorCorrectionTableInit(){
    $errorCorrectionTable.bootstrapTable('destroy');
    $errorCorrectionTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        // url: '/returnMoney/selectReturnMoneyList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "asc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        // serverSort: true,
        uniqueId: 'returnMoneyId',
        idField: 'returnMoneyId',
        pageSize: 10,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        // queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'returnMoneyId',visible: false},
            // {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '付款账号', field: 'paymentAccount', align: 'left', valign: 'middle'},
            {title: '付款单位', field: 'paymentUnitName', align: 'left', valign: 'middle'},
            {title: '到款时间',field: 'arriveTime', align: 'left', valign: 'middle'},
            {title: '到款金额',field: 'arriveMoney',align: 'left', valign: 'middle'},
            {title: '到款单位', field: 'arriveUnitName',align: 'left', valign: 'middle'},
            {title: '录入人', field: 'createByName',  align: 'left',valign: 'middle'},
            {title: '创建时间', field: 'createTm',  align: 'left',valign: 'middle'},
            {title: '操作', field: 'operationThing',  align: 'right',valign: 'middle'},

        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            $('#customerProductTableList').css({
                minWidth: $('#customerProductTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}





















































/*function viewCooperate2() {
    $('#cooperateTable').bootstrapTable('showLoading');
    viewCooperate(2);
}*/

/**
 * 功能：查看合作开发人员信息
 * */
function viewCooperate(type) {
    var contractId = $("#contractId").val();
    if (type == 2){
        contractId = $("#shiftContractId").val();
    }
    $.ajax({
        url: '/customerContract/selectContractCoDeveloperById',
        type: 'GET',
        dataType: 'json',
        data: {
            contractId: contractId
        },
        success: function (data) {
            if (data.code == '000000') {
                $('#cooperateTable').bootstrapTable('hideLoading').bootstrapTable('load', data.data);
            } else {
                $.alert('获取开发人员信息出错，代码：' + data.code);
            }
        },
        error: function (err) {
            $.alert('获取开发人员信息失败！');
            console.log(err);
        }
    })
}

function viewCooperate2(type) {
    var contractId = $("#contractId").val();
    if (type == 2){
        contractId = $("#shiftContractId").val();
    }
    $.ajax({
        url: '/customerContract/selectContractCoDeveloperById',
        type: 'GET',
        dataType: 'json',
        data: {
            contractId: contractId
        },
        success: function (data) {
            if (data.code == '000000') {
                $('#cooperateTable2').bootstrapTable('hideLoading').bootstrapTable('load', data.data);
            } else {
                $.alert('获取开发人员信息出错，代码：' + data.code);
            }
        },
        error: function (err) {
            $.alert('获取开发人员信息失败！');
            console.log(err);
        }
    })
}


function searchOrderInfo() {
    $.ajax({
        url: '/order/selectFinanceShiftOrderInfo?orderNumber='+$("#orderNumber").val(),
        type: 'POST',
        dataType: "json",
        // contentType: "application/json;charset=utf-8",

        success: (function (data) {
            if (data.code == "000000") {
                $("#shiftInfoDiv").show();
                $("#shiftOrderNumber").text(data.data.orderNumber);
                $("#shiftOrderActualTotalAmount").text(data.data.orderActualTotalAmount);
                $("#shiftCreatePeopleName").text(data.data.createPeopleName);
                $("#shiftCreateTm").text(data.data.createTm);
                $("#shiftContractCreateTm").text(data.data.createTm);
                $("#shiftContractType").text(getContractType(data.data.contractType));
                $("#shiftContractNumber").text(data.data.contractNumber);
                $("#shiftStarTime").text(data.data.contractStartDate);
                $("#shiftEndTime").text(data.data.contractEndDate);
                $("#coDeveloper").text(data.data.coDeveloperList);
                $("#shiftContractId").val(data.data.contractId);
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}


// 初始化合作开发人员信息列表
function cooperateTable() {
    $('#cooperateTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        striped: true,                      // 是否显示行间隔色
        undefinedText: '-',                 // cell没有值时显示
        pagination: true,                   // 是否显示分页
        pageSize: '5',                      // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: ['5', '10'],              // 可供选择的每页的行数
        columns: [
            {title: '合作开发人员', field: 'userName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '分配金额', field: 'allocationMount', align: 'left', valign: 'middle'},
        ]
    });
}

// 初始化合作开发人员信息列表
function cooperateTable1() {
    $('#cooperateTable2').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        striped: true,                      // 是否显示行间隔色
        undefinedText: '-',                 // cell没有值时显示
        pagination: true,                   // 是否显示分页
        pageSize: '5',                      // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: ['5', '10'],              // 可供选择的每页的行数
        columns: [
            {title: '合作开发人员', field: 'userName', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '分配金额', field: 'allocationMount', align: 'left', valign: 'middle'},
        ]
    });
}

//已删除审核按钮的提交
function allRightDel() {
    $.alert({
        title: '提示',
        content: "确定要进行退款吗？",
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    var len_selectedTable=$('#selectedList tbody tr')
                    var order_num=$('.order-num').html()
                    var residueMoney =$("#residueMoney").text();
                    let jsonCustomerId={
                        orderNumber:order_num,
                        residueMoney:residueMoney,
                        customerProductId:[]
                    }
                    $('#selectedList tbody tr').each(function () {
                        jsonCustomerId.customerProductId.push($(this).attr('data-uniqueid'))
                    })
                    $.ajax({
                        url:'/orderDetail/delOrderDetail',
                        type: 'POST',
                        dataType: "json",
                        contentType: "application/json;charset=utf-8",
                        data: JSON.stringify(jsonCustomerId),
                        success: (function (data) {
                            if(data.code == '000000'){
                                $.alert({
                                    title: '提示',
                                    content: '操作成功！',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                window.location.reload();
                                            }
                                        }
                                    }
                                });
                            }else {
                                $.alert(data.message);
                            }
                        }),
                        error: (function (res) {

                        })
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                }
            }
        }
    })
}
/**
 * 获取产品列表初始化表格
 * */
function productList() {
    $productTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/order/financeOrderInfo?productOrderId='+$("#orderCode").val(),
        method: 'get',
        //search: true,
        //visibleSearch: true,
        //customSearch: customSearch,
        pagination: true,
        pageSize: 5,
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        columns: [
            {field: 'customerProductId', title: 'id', visible: false},
            {field: 'productName', title: '产品名称'},
            {field: 'money', title: '价格', formatter: ifMoneyShowOrHide},
            {field: 'productQuantity', title: '数量', formatter: ifMoneyShowOrHide},
            //{field: 'operate', title: '操作', align: 'center', width: '100', formatter: operateFormatter},
        ],
        formatNoMatches:function(){
            return "暂无产品";
        },
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data
                };
            } else {
                var obj = {
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {

        }
    })
}


//产品删除记录
function productDeletion() {
    $productDelRecord.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order/orderBackMoneyList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderDetailId',
        idField: 'orderRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        // fixedColumns: true,     // 冻结列
        // fixedNumber: 1,         // 左侧固定列
        // fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                sortName : params.sort, //排序列名
                sortOrder : params.order,//排序方式
                productOrderId: $('#orderCode').val(),
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'productOrderId', visible: false},
            {title: '产品名称',field: 'productName', align: 'left', valign: 'middle'},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '产品成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '申请退款金额', field: 'applyBackMoney', align: 'left', valign: 'middle'},
            {title: '服务费', field: 'serviceMoney', align: 'left', valign: 'middle'},
            {title: '实际退款金额', field: 'backMoney', align: 'left', valign: 'middle'},
            {title: '审核人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '审核时间', field: 'updateTm', align: 'left', valign: 'middle'},
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                // $('#applyBackMoney').text(result.data.applyBackMoney)
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            console.log(data)
        },
    });
}

/**
 * 自定义搜索
 * data:    表格数据
 * text:    搜索的文字
 * filter:  filterBy方法中的过滤器对象
 * */
function customSearch(data, text) {
    return data.filter(function (row) {
        return (row.productName+"").indexOf(text) > -1
    });
}

// 自定义添加操作
function operateFormatter(value, row, index) {
    //\'' + row.returnMoneyId + '\',
    var result = '<button type="button" class="btn btn-default" onclick="btnOperate(\'' + row.customerProductId + '\', \'' + row.productName + '\',\'' + row.money + '\', true,\'' + row.productOrderDetailType + '\')"><i class=""></i>删除产品</button>';
    return result;
}

// 自定义编辑操作
function enterPayMent(value, row, index) {
    var result ="";
    result += '<button type="button" data-toggle="modal" data-target="#addInputMoney" class="btn btn-default" onclick="btnEdit(\''+row.returnMoneyId+'\',\''+row.paymentUnitName+'\',\''+row.arriveTime+'\',\''+row.arriveMoney+'\',\''+row.arriveUnitName+'\',\''+row.paymentAccount+'\',\''+row.arriveMethod+'\',\''+row.arriveAccountType+'\',\''+row.remark+'\',\''+row.paymentBank+'\',\''+row.serial+'\')"><i class=""></i>编辑</button>';
    result += '<button type="button" class="btn btn-default btn-danger" onclick="delReturnMoney(this, \''+row.returnMoneyId+'\')"><i class=""></i>删除</button>';
    result += '<button type="button" data-toggle="modal" data-target="#errorShift" class="btn btn-default btn-danger" onclick="errorShift(\''+row.returnMoneyId+'\')"><i class=""></i>错误关联</button>';
    return result;
}

function errorShift() {
    var returnMoneyId = $('#orderCode').val()
    console.log()
    $("#shiftReturnMoneyIdHide").val(returnMoneyId);

}


function delReturnMoney(that, returnMoneyId) {
    var $this = $(that);
    $.alert({
        title: '提示',
        content: "确定要删除回款信息吗？",
        buttons: {
            cancel: {
                text: '取消',
                btnClass: 'btn-link',
            },
            confirm: {
                text: '删除',
                btnClass: 'btn-danger',
                action: function () {
                    // 删除操作后禁用当前删除按钮，防止多次提交删除操作
                    $(this.$$confirm[0]).prop('disabled', true);
                    $this.prop('disabled', true);

                    $.ajax({
                        type: "post",
                        url: "/returnMoney/delReturnMoney",
                        data: {
                            returnMoneyId: returnMoneyId
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $.alert('操作成功!');
                                window.location.reload();
                            } else {
                                $.alert(data.message);
                            }
                        },
                        error: function () {
                            $.alert('删除失败，请稍后再试!');
                        }
                    });
                }
            },
        }
    })
}

function btnEdit(returnMoneyId,paymentUnitName,arriveTime,arriveMoney,arriveUnitName,paymentAccount,arriveMethod,arriveAccountType,remark,paymentBank,serial) {
    $('#returnMoneyIdHide').val(returnMoneyId) //回款id
    // arriveTime = arriveTime.substring(0,10);
    $('#arriveTime').val(arriveTime) //到款时间
    if ("null" != arriveMoney){
        $('#arriveMoney').val(arriveMoney) //到款金额
    }
    $('#arriveMethod').val(arriveMethod).selectpicker('refresh') //到款方式

    $('#arriveAccountType').val(arriveAccountType) //到款账号类型
    $('#arriveAccountType').selectpicker('refresh');
    if ("null" != remark ){
        $('#remark').val(remark) //备注
    }
    if ("null" != paymentAccount){
        $('#paymentAccount').val(paymentAccount) //付款账号
    }
    if ("null" != paymentBank){
        $('#paymentBank').val(paymentBank) //付款银行
    }
    if ("null" != paymentUnitName){
        $('#paymentUnit').val(paymentUnitName) //付款单位
    }
    if ("null" != serial){
        $('#serial').val(serial) //流水号
    }

    hideorShouDiv(1);
}



//最后一次填写的服务费金额
var maxServiceMoney = 0;
/**
 * 点击添加事件
 * productId:       产品id
 * productName:     产品名称
 * flag:            添加删除控制开关
 * */
function btnOperate(customerProductId, productName,money, flag,type) {
    if (type && type == 2){
        promptInfo("活动产品不能删除!");
        return;
    }else if (type && type ==3){
        promptInfo("赠品产品不能删除!");
        return;
    }
    var tableA = $productTable;
    var tableB = $selectedTable;
    if (!flag) {
        tableA = $selectedTable;
        tableB = $productTable;
    }
    // 删除操作
    tableA.bootstrapTable('remove', {field: 'customerProductId', values: customerProductId});
    // 添加操作
    tableB.bootstrapTable('insertRow', {
        index: 0,
        row: {
            customerProductId: customerProductId,
            productName: productName,
            money: money,
            operate: '<button type="button" class="btn btn-default" onclick="btnOperate(\'' + customerProductId + '\', \'' + productName + '\', \'' + money + '\', false,null)"><i class=""></i>恢复</button>'
        }
    });
    //计算金额
    var contMoney = $("#countMoney").text();
    var residueMoney = $("#residueMoney").text();
    var allMoney = $("#orderActualTotalAmount").text();
    var backMoneySpan =$("#backMoneySpan").text();
    //目前回款
    var returnMoneyAmount = parseFloat($("#returnMoneyAmountspan").text());
    money = parseFloat(money);
    if (flag){
        //如果当前需退款金额大于当前回款金额：只退当前回款金额。
        if (money >= returnMoneyAmount){
            $("#backMoneySpan").text(returnMoneyAmount);
            $("#residueMoney").text(0);
            return;
        }
        if (maxServiceMoney){
            maxServiceMoney = parseFloat(maxServiceMoney);
        }
        //当前需退款金额小于当前回款金额时。
        if (money < returnMoneyAmount){

            backMoneySpan = accAdd(backMoneySpan,money);
            if (backMoneySpan >contMoney){
                backMoneySpan = contMoney;
            }
            $("#backMoneySpan").text(backMoneySpan);
            $("#residueMoney").text(accSubtr(contMoney,backMoneySpan));
            //有服务费
            if (maxServiceMoney > 0){
                backMoneySpan = accSubtr($("#backMoneySpan").text(),maxServiceMoney);
                residueMoney = accAdd($("#residueMoney").text(),maxServiceMoney);
                if (backMoneySpan < maxServiceMoney){
                    //当应退款小于手续费时：总回款-服务费
                    backMoneySpan = accSubtr(contMoney,maxServiceMoney);
                    residueMoney = maxServiceMoney;
                }
                $("#backMoneySpan").text(backMoneySpan);
                $("#residueMoney").text(residueMoney);
                return;
            }


            //有服务费
            /*if (maxServiceMoney > 0){
                //backMoneySpan = accSubtr(accSubtr(returnMoneyAmount,money),maxServiceMoney);
                backMoneySpan = accSubtr(money,maxServiceMoney);
                if (backMoneySpan < 0){
                    //应退款出现负数时，设置成回款金额
                    $("#backMoneySpan").text(returnMoneyAmount);
                }else {
                    $("#backMoneySpan").text(backMoneySpan);
                }
                //退款为负数归零
                if (backMoneySpan < 0){
                    backMoneySpan = 0;
                }
                $("#residueMoney").text(backMoneySpan);
                return;
            }else { //没有服务费
                backMoneySpan = accAdd(backMoneySpan,money);
                if (backMoneySpan >contMoney){
                    backMoneySpan = contMoney;
                }
                $("#backMoneySpan").text(backMoneySpan);
                $("#residueMoney").text(accSubtr(contMoney,backMoneySpan));
                return;
            }*/
        }

    }else {
        var backMoney = parseFloat($("#backMoneySpan").text());
        var residueMoney = parseFloat($("#residueMoney").text());
        //当前应退款金额小于当前退款价格时，点击恢复后应退款为0
        if (backMoney < money){
            $("#backMoneySpan").text(0);
        }else {
            //应退款-价格
            backMoneySpan = accSubtr(backMoney,money);
            if (maxServiceMoney > 0 ){
                //应退款-价格-服务费
                backMoneySpan = accSubtr(accSubtr(backMoney,money),maxServiceMoney);
            }
            if (backMoneySpan < 0){
                $("#backMoneySpan").text(0);
                $("#residueMoney").text(returnMoneyAmount);
            }else {
                $("#backMoneySpan").text(backMoneySpan);
                $("#residueMoney").text(accSubtr(returnMoneyAmount,backMoneySpan));
            }
        }
        //假装没有设置过手续费
        maxServiceMoney = 0;
        $("#serviceMoney").val("");
    }

}

//计算金额
function calculateMoney() {
    //应退款
    var backMoney = parseFloat($("#backMoneySpan").text());
    var residueMoney = parseFloat($("#residueMoney").text());
    var countMoney = parseFloat($("#countMoney").text());
    //maxServiceMoney大于0时，代表原来设置过手续费，先清除原来设置的手续费
    if (parseFloat(maxServiceMoney) > 0){
        var backMoney = accAdd(backMoney,maxServiceMoney);
        if (backMoney < 0){
            $("#backMoneySpan").text(0);
        }else {
            $("#backMoneySpan").text(backMoney);
        }
        $("#residueMoney").text(accSubtr(residueMoney,maxServiceMoney));
    }
    //服务费
    var serviceMoney =$("#serviceMoney").val();
    if (serviceMoney > 0){
        maxServiceMoney = serviceMoney;
    }
    //没有选退款产品时直接跳出
    if (0 == backMoney){
        return;
    }
    //重新获取各个金额
    backMoney = parseFloat($("#backMoneySpan").text());
    residueMoney = parseFloat($("#residueMoney").text());
    countMoney = parseFloat($("#countMoney").text());
    if (serviceMoney >0){
        serviceMoney = parseFloat(serviceMoney);
        if (residueMoney > 0){
            if (backMoney > 0){
                //当前应退款减服务费
                $("#backMoneySpan").text(accSubtr(backMoney,serviceMoney));
                //$("#backMoneySpan").text(accAdd(backMoney,serviceMoney));
            }else {
                //当前应退为0时，直接把输入的服务费填上
                $("#backMoneySpan").text(serviceMoney);
            }
            //当前剩余总款加服务费
            residueMoney = accAdd(residueMoney,serviceMoney);
            $("#residueMoney").text(residueMoney);
        }
        if (residueMoney < 0){
            $("#backMoneySpan").text(countMoney);
            $("#residueMoney").text(0);
        }
    }

    //如果没有选中要删除的产品或删除产品的总价等于订单总金额
    /*if ("" == $("#backMoneySpan").text() || $("#residueMoney").text() == $("#countMoney").text()){
        //应退
        $("#backMoneySpan").text(accSubtr(0,serviceMoney));
        //剩余总款
        var contMoney = $("#countMoney").text();
        contMoney = accAdd(contMoney,serviceMoney);
        $("#residueMoney").text(contMoney);
        maxServiceMoney = serviceMoney;
    }else if (serviceMoney > 0){    //服务费>0
        //如果全部退款，剩余总款为0时，直接把服务费算上
        if ($("#residueMoney").text() ==0 && serviceMoney > 0){
            $("#residueMoney").text(serviceMoney);
            $("#backMoneySpan").text(accSubtr($("#backMoneySpan").text(),serviceMoney));
        }else {
            //应退款
            var backMoney = $("#backMoneySpan").text();
            backMoney = accSubtr(backMoney,serviceMoney);
            $("#backMoneySpan").text(backMoney);

            //总款减去应退款
            var contMoney = $("#countMoney").text();
            contMoney = accAdd($("#residueMoney").text(),backMoney);
            //剩余总款
            $("#residueMoney").text(contMoney);
            maxServiceMoney = serviceMoney;
        }

    }else if(maxServiceMoney > 0){ //当前设置服务费等于0，但是剩余总款和应退已计算了上次输入的服务费
        //剩余总款
        var residueMoney = $("#residueMoney").text();
        residueMoney = accSubtr(residueMoney,maxServiceMoney);
        $("#residueMoney").text(residueMoney);
        //应退
        var backMoney = $("#backMoneySpan").text();
        backMoney = accAdd(backMoney,maxServiceMoney);
        $("#backMoneySpan").text(backMoney);
        maxServiceMoney = 0;
    }*/



}




function inputPayment() {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '录入回款',
        url : "/front/finance/inputPayment?productOrderId=" + $("#orderCode").val()
    }, true);
}

function queryParams2(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    //搜索条件
    params.orderId = $("#orderCode").val();
    return params;
}
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}


/**
 * 加载全部公司信息并且赋值到select框
 */
function loadAllCompanyList(name) {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">请选择</option>';
            data.data.map(function (item) {
                if (name == "arriveUnitName"){
                    companyOptionHtml += '<option value="' + item.companyName + '">' + item.companyName + '</option>';
                }else {
                    companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
                }
            });
            $('#'+name).html("");
            $('#'+name).append(companyOptionHtml);
            $('#'+name).selectpicker('refresh');
        }
    });
}

/**
 * 获得客户名称下拉
 */
/*function getCustomerSelect(){
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/customerController/getCustomerListByComp',
        cache : false,
        data:{
        },
        async : false,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '<option value="">请选择</option>';
                $.each(data.data, function(n, value) {
                    html += "<option value=" + value.customerId + ">" +  value.customerName + "</option>";
                });

                $('#customerId').html(html).selectpicker('refresh');
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}*/



function dateModule() {
    // 回款日期
    $('#arriveTime').daterangepicker({
        maxDate: new Date(),
        singleDatePicker: true,
        timePicker: true,
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            cancelLabel: '清空',
        },
        timePicker24Hour : true,
        autoUpdateInput: false,
    });
    $('#arriveTime').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD HH:mm'));
    });
    $('#arriveTime').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });
    // 初始化select控件
    /*$('form select:not("#giftList")').selectpicker({
        noneSelectedText: '请选择',
        sanitize: true,
        size: 10
    });

    // 初始化日期选择控件
    $('.date-input').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    // 日期选择控件
    $('#arriveTime').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    // 日期选择控件
    $('#renewContractStartTime').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });


    // 提成录入时间
    $('#royaltyRecordTime').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });*/
}




/**
 * 加法
 * @param arg1
 * @param arg2
 * @returns
 */
function accAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0};
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0};
    m=Math.pow(10,Math.max(r1,r2));
    return (arg1*m+arg2*m)/m;
}

/**
 * 减法
 * @param arg1
 * @param arg2
 * @returns
 */
function accSubtr(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
    try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
    m=Math.pow(10,Math.max(r1,r2));
    //动态控制精度长度
    n=(r1>=r2)?r1:r2;
    return ((arg1*m-arg2*m)/m).toFixed(n);
}

/***
 * 乘法，获取精确乘法的结果值
 * @param arg1
 * @param arg2
 * @returns
 */
function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){};
    try{m+=s2.split(".")[1].length}catch(e){};
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}

/***
 * 除法，获取精确乘法的结果值
 * @param arg1
 * @param arg2
 * @returns
 */
function accDivCoupon(arg1,arg2){
    var t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length;}catch(e){}
    try{t2=arg2.toString().split(".")[1].length;}catch(e){}
    with(Math){
        r1=Number(arg1.toString().replace(".",""));
        r2=Number(arg2.toString().replace(".",""));
        return (r1/r2)*pow(10,t2-t1);
    }
}



//隐藏或显示div
function hideorShouDiv(type) {
    /*var status = $("#arriveMethod").val();
    if (status > 0 || type >0){
        console.info("1111")
        $('#paymentAccountDiv').modal('hide');
        $('#paymentBankDiv').modal('hide');
        $('#serialDiv').modal('hide');
    }else{
        console.info("2222")
        $('#paymentAccountDiv').modal('show');
        $('#paymentBankDiv').modal('show');
        $('#serialDiv').modal('show');

    }*/

}

function getContractType(contractType){
    if (1 == contractType){
        return "非会员合同";
    }
    if (2 == contractType){
        return "会员新单合同";
    }
    if (3 == contractType){
        return "活动合同";
    }
    if (4 == contractType){
        return "会员续费合同";
    }
    if (5 == contractType){
        return "兑换合同";
    }
    if (6 == contractType){
        return "单品合同";
    }
    if (7 == contractType){
        return "会员单次合同";
    }
}



function ifMoneyShowOrHide(value, row, index) {
    if (row.productOrderDetailType == 2 || row.productOrderDetailType == 3){
        return "-";
    }
    return value;
}

function subStringArriveTime(value, row, index) {
    if (value){
        return value.toString().substring(0,10);
    }
    return value;
}

function submitDismiss() {
    if($('#removeNote').val() == ''){
        $.alert('请填写解除关联备注');
        return ;
    }
    $.ajax({
        url: '/bankFlowExamine/relieveRelationByOrderId',
        type: 'POST',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {
            productOrderId:$('#orderCode').val(),  //客户id
            relationReason:$('#removeNote').val(),
        },
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '温馨提示',
                    content: data.message,
                    scrollToPreviousElement: false,
                    scrollToPreviousElementAnimate: false,
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function(){
                                $('#dismiss').modal('hide');
                                window.location.reload();
                                openTab("流水审核", "/front/finance/bankFlowExamine");
                                refreshActivePane('/front/finance/bankFlowExamine');
                                $('#removeNote').val('')
                            }
                        }
                    }
                });
            }else{
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}

$('#serial').on('blur',function(){
    if($('#serial').val() == ''){
        return ;
    }
    $.ajax({
        url: '/bankFlow/queryData',
        type: 'get',
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        data: {
            transactionNo:$('#serial').val(),
        },
        success: (function (result) {
            if (result.code == "000000") {
                let data = result.data[0];
                $('#arriveTime').val(data.transactionDate);
                $('#paymentUnit').val(data.oppositeCompany);
                $('#paymentAccount').val(data.oppositeBankAccount);
                $('#paymentBank').val(data.oppositeBank);
                $('#arriveAccountType').val(data.payeeName).selectpicker('refresh');
            }else{
                $.alert(result.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
})